package com.example.zce.back.common.oss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.BucketInfo;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.example.zce.library.common.utils.UUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * 描述：
 *
 * @author zengyz
 * @date 2018/8/8 9:13
 */
@Service
public class AliOSS {

    private static Logger log=LoggerFactory.getLogger(AliOSS.class);

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.access.key.id}")
    private String accessKeyId;
    @Value("${aliyun.oss.access.key.secret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.access.bucket.name}")
    private String bucketName;

    @Value("${aliyun.oss.img.path}")
    private String imgPath;

    public String uploadOSS(String key,byte[] file){
        log.debug("开始上传");
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            if (ossClient.doesBucketExist(bucketName)) {
                log.debug("您已经创建Bucket：" + bucketName + "。");
            } else {
                log.debug("您的Bucket不存在，创建Bucket：" + bucketName + "。");
                ossClient.createBucket(bucketName);
            }
            BucketInfo info = ossClient.getBucketInfo(bucketName);
            InputStream is = new ByteArrayInputStream(file);
            String filename=key+"_"+UUIDUtils.getUUID08();
            ossClient.putObject(bucketName, filename, is);
            log.debug("Object：" + filename + "存入OSS成功。");
            return imgPath+filename;
        } catch (Exception e) {
           return null;
        } finally {
            ossClient.shutdown();
        }
    }
}
